package com.edu.edu.day9_19_week7_homework.activity;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.edu.edu.day9_19_week7_homework.Contans;
import com.edu.edu.day9_19_week7_homework.R;
import com.edu.edu.day9_19_week7_homework.SQLite.DBHelpter;
import com.edu.edu.day9_19_week7_homework.adapter.MyPageAdapter;
import com.edu.edu.day9_19_week7_homework.bean.TopTitles;
import com.edu.edu.day9_19_week7_homework.fragment.ContentFragment;
import com.edu.edu.day9_19_week7_homework.thread.LoadTitleJsonTask;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MainActivity extends AppCompatActivity implements LoadTitleJsonTask.onGetJsonTitleResult,View.OnClickListener{

    private DrawerLayout drawer;
    private ViewPager mVp;
    private TabLayout tabs;
    private Toolbar toolbar;
    private List<TopTitles> mList;
    private DBHelpter dbHelpter;
    private SQLiteDatabase mDb;
//    private ListView mLv;
//    private TextView tvTel;
//    private Button bt_login;
//    private Button bt_register;
    private FloatingActionButton mFloatButton;
    private NavigationView mNavigationView;
    private Button bt_login;
    private Button bt_register;
    private ImageView header_image;
    private TextView header_tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //去除标题
        supportRequestWindowFeature(getWindow().FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //当播放完视频，点击返回按钮的时候将屏幕设置为竖屏
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        initView();//初始化控件
        initDrawer();//抽屉监听
        initIetmClick();//抽屉外面按钮点击事件
        //initDrawerOut();//抽屉外面内容
        initAdapter();//初始化适配器
    }

    private void initIetmClick() {
        //抽屉外面关联menu的点击事件
        mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()){
                    //登录注册按钮的点击事件
//                    case R.id.bt_login://登陆页面
//                        if(bt_login.getText().equals("登录")){startActivity(new Intent(MainActivity.this,LoginActivity.class));
//                        }else if(bt_login.getText().equals("注销")){
//                            finish();
//                            Toast.makeText(MainActivity.this,"账户已注销，请重新登录！ ",Toast.LENGTH_LONG).show();
//                        }
//                        break;
//                    case R.id.bt_register://注册按钮
//                        startActivity(new Intent(MainActivity.this,RegisterActivity.class));
//                        break;
                    case R.id.action_collect://收藏按钮
                        //点击进入收藏页面
                        Intent intentS = new Intent(MainActivity.this, CollectActivity.class);
                        startActivity(intentS);
                        break;
                    case R.id.action_clear://清除按钮
                        //点击删除收藏记录
                        dbHelpter =     new DBHelpter(MainActivity.this);
                        mDb = dbHelpter.getWritableDatabase();
                        int id = mDb.delete("food", null, null);
                        if(id > 0){
                            Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_LONG).show();
                        }else{
                            Toast.makeText(MainActivity.this,"删除失败",Toast.LENGTH_LONG).show();
                        }
                        break;
                }
                return false;
            }
        });
        //浮动按钮点击事件
        mFloatButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar snackbar = Snackbar.make(view, "点击进入视频页面", Snackbar.LENGTH_INDEFINITE).setAction("点击", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Toast.makeText(MainActivity.this, "被点击了", Toast.LENGTH_LONG).show();
                    }
                }).setActionTextColor(Color.RED);
                //展示出来
                snackbar.show();
                //snackbar.dismiss();
            }
        });
    }

    private void initDrawerOut() {
        int[] imagesId = getImagesId();
        String[] function = getFunction();
        //添加数据源
        List<Map<String,Object>> data = new ArrayList<>();
        for (int i = 0; i < imagesId.length; i++) {
            Map<String,Object> map = new HashMap<>();
            map.put("images",imagesId[i]);
            map.put("function",function[i]);
            data.add(map);
        }
//        assert mLv != null;
//        SimpleAdapter adapter = new SimpleAdapter(MainActivity.this,data,R.layout.drawer_list_item,new String[]{"images","function"},new int[]{R.id.drawer_list_image,R.id.drawer_list_text});
//        mLv.setAdapter(adapter);
    }

    private void initAdapter() {
//        final String[] titles= getResources().getStringArray(R.array.titles);
        new LoadTitleJsonTask(this).execute(Contans.INDEX_URL);
    }
    //回调标题数据
    @Override
    public void onGetTitleResult(List<TopTitles> result) {
        mList = new ArrayList<>();
        mList = result;
        List<String> title = new ArrayList<>();
        List<Fragment> fargments = new ArrayList<>();
        for (int i = 0; i < mList.size(); i++) {
            Fragment fragment = ContentFragment.createFragment(i);
            tabs.getTabAt(i);
            TopTitles topTitles = mList.get(i);
            String name = topTitles.getName();
            //利用bundle传url到fragment
            Bundle bundle =new Bundle();
            //获取url的id
            String id = topTitles.getId();
            //利用replace方法将"%@"与获取的id替换
            String format = Contans.JSON_URL.replace("%@", id);
            bundle.putString("key",format);
            fragment.setArguments(bundle);
            title.add(name);
            fargments.add(fragment);
        }
        //创建适配器
        final MyPageAdapter adapter = new MyPageAdapter(getSupportFragmentManager(),fargments,title);
        assert adapter != null;
        //设置viewpager适配器
        mVp.setAdapter(adapter);
        //联动监听
        tabs.setupWithViewPager(mVp);
    }

    private void initView() {
        //抽屉里面
        drawer = (DrawerLayout) findViewById(R.id.drawer);
        tabs = (TabLayout) findViewById(R.id.tab);
        mVp = (ViewPager) findViewById(R.id.main_vp);
        toolbar =  (Toolbar) findViewById(R.id.toolbar);
        mFloatButton = (FloatingActionButton) findViewById(R.id.drawer_out_float);
        //抽屉外面
        mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
        LinearLayout headerView = (LinearLayout) mNavigationView.getHeaderView(0);//头部关联的第一个布局,索引为0
        header_image = (ImageView) headerView.findViewById(R.id.header_image);
        header_tv = (TextView) headerView.findViewById(R.id.header_tv);
        bt_login = (Button) headerView.findViewById(R.id.bt_login);
        bt_register = (Button) headerView.findViewById(R.id.bt_register);
        bt_login.setOnClickListener(this);
        bt_register.setOnClickListener(this);
        //设置默认头像机器人
        header_image.setImageResource(R.mipmap.ic_launcher);

        Intent intentTel = getIntent();
        String phone = intentTel.getStringExtra("phone");
        String str = intentTel.getStringExtra("str");
        if(str != null && phone != null){
            header_image.setImageResource(R.mipmap.image00);//登录成功之后设置头像
            header_tv.setVisibility(View.VISIBLE);//设置可见
            header_tv.setText("账户:"+phone);
            bt_login.setText(str);
            //设置按钮不可点击
            bt_register.setClickable(false);
            //修改按钮颜色
            bt_login.setBackgroundColor(Color.GRAY);
            bt_register.setBackgroundColor(Color.RED);
        }

//        ImageView image = (ImageView) findViewById(R.id.drawer_image);
//        tvTel = (TextView) findViewById(R.id.main_tel);
//        bt_login = (Button) findViewById(R.id.drawer_bt_login);
//        bt_register = (Button) findViewById(R.id.drawer_bt_register);
//        mLv = (ListView) findViewById(R.id.drawer_list);
        //获取电话号码
        //tvTel.setVisibility(View.GONE);//默认不显示
//        Intent intentTel = getIntent();
//        String phone = intentTel.getStringExtra("phone");
//        String str = intentTel.getStringExtra("str");
//        if(str != null && phone != null){
//            image.setBackgroundResource(R.mipmap.image00);//登录成功之后设置头像
//            tvTel.setVisibility(View.VISIBLE);//设置可见
//            tvTel.setText("账户:"+phone);
//            bt_login.setText(str);
//            //设置按钮不可点击
//            bt_register.setClickable(false);
//            //修改按钮颜色
//            bt_login.setBackgroundColor(Color.GRAY);
//            bt_register.setBackgroundColor(Color.RED);
//        }
//        //点击事件
//        mLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//
//            @Override
//            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
//                //判断点击条目
//                if(position==1){
//                    //点击进入收藏页面
//                    Intent intentS = new Intent(MainActivity.this, CollectActivity.class);
//                    startActivity(intentS);
//                }else if(position==5){
//                    //点击删除收藏记录
//                    dbHelpter =     new DBHelpter(MainActivity.this);
//                    mDb = dbHelpter.getWritableDatabase();
//                    int id = mDb.delete("food", null, null);
//                    if(id > 0){
//                        Toast.makeText(MainActivity.this,"删除成功",Toast.LENGTH_LONG).show();
//                    }else{
//                        Toast.makeText(MainActivity.this,"删除失败",Toast.LENGTH_LONG).show();
//                    }
//                }else{
//                    Toast.makeText(MainActivity.this,"当前无数据",Toast.LENGTH_LONG).show();
//                }
//
//            }
//        });

    }

    private void initDrawer() {
//        //抽屉开关监听
//        ActionBarDrawerToggle mToggle = new ActionBarDrawerToggle(MainActivity.this, drawer, toolbar, 0, 0);
//        //同步抽屉状态
//        mToggle.syncState();
//        //设置抽屉监听
//        assert  mToggle != null;
//        drawer.addDrawerListener(mToggle);
        //填充菜单
        toolbar.inflateMenu(R.menu.over_item);
        //设置溢出菜单的图标
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//API21{
            toolbar.setOverflowIcon(getResources().getDrawable(R.mipmap.ic_menu_more_overflow));
        }
        //开关抽屉
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!drawer.isDrawerOpen(GravityCompat.START)){
                    drawer.openDrawer(GravityCompat.START);
                }else{
                    //关闭抽屉
                    drawer.closeDrawers();
                }
            }
        });
    }

    public int[] getImagesId() {
        return new int[]{R.mipmap.image01,R.mipmap.image02,R.mipmap.image03,R.mipmap.image04,R.mipmap.image05,R.mipmap.image06};
    }

    public String[] getFunction() {
        return new String[]{"我的账号","收藏","通用","意见反馈","检测更新","清除下载"};
    }

    //点击进入登录页面
//    public void login(View view) {
//        if(bt_login.getText().equals("登录")){
//            startActivity(new Intent(MainActivity.this,LoginActivity.class));
//        }else if(bt_login.getText().equals("注销")){
//            finish();
//            Toast.makeText(MainActivity.this,"账户已注销，请重新登录！ ",Toast.LENGTH_LONG).show();
//        }
//    }

    //点击进入注册页面
//    public void register(View view) {
//        startActivity(new Intent(MainActivity.this,RegisterActivity.class));
//    }
    //处理返回键
    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    //登录注册按钮点击事件
    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.bt_login://登陆页面
                if(bt_login.getText().equals("登录")){startActivity(new Intent(MainActivity.this,LoginActivity.class));
                }else if(bt_login.getText().equals("注销")){
                    finish();
                    Toast.makeText(MainActivity.this,"账户已注销，请重新登录！ ",Toast.LENGTH_LONG).show();
                }
                break;
            case R.id.bt_register://注册按钮
                startActivity(new Intent(MainActivity.this,RegisterActivity.class));
                break;
        }
    }
}
